package com.solocredit.finance.ui.main.fm

import android.Manifest
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.adapter.MullaOnItemChildClickListener
import com.solocredit.finance.base.utils.permission.OnPermissionCallback
import com.solocredit.finance.base.utils.permission.XXPermissions
import com.solocredit.finance.databinding.FmMullaHomeBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpFm
import com.solocredit.finance.ui.main.adapter.MullaProductAdapter
import com.solocredit.finance.ui.main.impl.MullaHomePresenterImpl
import com.solocredit.finance.ui.main.view.IMullaHomeView
import com.solocredit.finance.ui.market.act.MullaApplyAct
import com.solocredit.finance.ui.market.act.MullaOrderDetailsAct
import com.solocredit.finance.ui.steps.act.MullaStepsAct
import com.solocredit.finance.ui.user.act.MullaUserLuckyDrawAct
import com.solocredit.finance.ui.user.act.MullaUserMessageAct
import com.solocredit.finance.utils.dialog.PermissionListDialog
import com.solocredit.finance.utils.event.MullaBehaviorTracker
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.utils.helper.TestDataLibInvoke
import org.json.JSONObject
import androidx.core.graphics.toColorInt
import com.solocredit.finance.config.MullaConfigs

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:57
 * @Annotation：首页
 */
class MullaHomeFm : MvpFm<IMullaHomeView, MullaHomePresenterImpl>(),IMullaHomeView {
//    lateinit var binding: FmMullaHomeBinding
    private var _binding: FmMullaHomeBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var pAdapter: MullaProductAdapter? = null

    override fun createPresenter(): MullaHomePresenterImpl {
        return MullaHomePresenterImpl(context)
    }

    override fun getMullaRootView(inflater: LayoutInflater): View {
        _binding = FmMullaHomeBinding.inflate(inflater)
        return binding.root
    }

    override fun initMullaView() {
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor("#FFFFFFFF".toColorInt())
        setMullaBackBtnRes(R.mipmap.mulla_kefu_dialog_icon)
        setMullaRightBtnRes(R.mipmap.mulla_message_icon)
        setMullaTextTitle(getString(R.string.home_title))
        rootViewBinding.containerLayout.setBackgroundColor("#FFFFFFFF".toColorInt())
        isInterceptBack(true)
        initMullaRefreshLayout()
        initMullaRecyclerView()

        val showTipsKey = getString(R.string.home_credit_score_result)
        val showTipsText = String.format(getString(R.string.home_credit_score_tips),showTipsKey)
        val spString = SpannableString(showTipsText)
        val start = showTipsText.indexOf(showTipsKey)
        spString.setSpan(ForegroundColorSpan("#FFFFAC25".toColorInt()), start, showTipsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textScoreTips?.text = spString
    }

    override fun initMullaListener() {
        rootViewBinding.ivBaseBack.setOnClickListener {
            showMullaKefuDialog("Home Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Home Page")
        }
        rootViewBinding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"Home Page")
            showMullaLanguageDialog("Home Page", onSelectCallback = {
            })
        }
        rootViewBinding.ivFun.setOnClickListener {
            onIntent(MullaUserMessageAct::class.java)
        }
        //抽奖
        _binding?.luckydrawLayout?.btnGo?.setOnClickListener {
            onIntent(MullaUserLuckyDrawAct::class.java)
        }
        //产品列表
        _binding?.productLayout?.setOnClickListener {
            if (presenter.isApply()) {
                return@setOnClickListener
            }
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.GONE

            showMullaLoading(isTOuchOut = false, isCancel = false)
            presenter.checkMullaProductStatus(true)
        }
        //已申请列表
        _binding?.appliedLayout?.setOnClickListener {
            if (!presenter.isApply()) {
                return@setOnClickListener
            }
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.GONE

            showMullaLoading(isTOuchOut = false, isCancel = false)
            presenter.checkMullaProductStatus(false)
        }
        // Apply Now 、 Repay Now
        _binding?.textEmpty?.setOnClickListener {
            if (presenter.isApply()){//apply now
                MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_SHOW_REPAY))
            } else {
                _binding?.productLayout?.callOnClick()
            }
        }
    }

    override fun initMullaData() {
        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.visibility = View.GONE
        } else {
            _binding?.licenseLayout?.removeAllViews()
            _binding?.licenseLayout?.addView(licenseView())
            _binding?.licenseLayout?.visibility = View.VISIBLE
        }

        presenter.checkMullaProductStatus(true)
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PRODUCT_LIST_START)
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //刷新流程
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PROCESS_REFRESH))
            //刷新产品列表
            MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_REFRESH))
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 初始化产品列表
     */
    private fun initMullaRecyclerView() {
        _binding?.recyclerView?.setHasFixedSize(true)
        _binding?.recyclerView?.isNestedScrollingEnabled = false
        _binding?.recyclerView?.isFocusableInTouchMode = false //不需要焦点
        _binding?.recyclerView?.layoutManager = LinearLayoutManager(context)
        pAdapter = MullaProductAdapter(_binding?.recyclerView)
        _binding?.recyclerView?.adapter = pAdapter
        _binding?.recyclerView?.itemAnimator = DefaultItemAnimator()
        pAdapter?.setOnItemChildClickListener(MullaOnItemChildClickListener { _, childView, position ->
            val item = pAdapter?.getItem(position)
            item?.let {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_HOME_PRODUCT, it.optString("product"))
                // TODO: apply 批量埋点上报
                MullaBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)

                presenter.onMullaSetSelectProductInfo(it)
                when (childView.id) {
                    R.id.itemLayout -> {//点击Item
                        //只有 Applied列表才可点击查看详情
                        if (!it.optBoolean("isApply", false)) {
                            val pLogo = it.optString("logo")
                            val pName = it.optString("product")
                            val pToken = it.optString("token")
                            val pTitle = it.optString("name")
                            MullaOrderDetailsAct.start(requireContext(), pLogo, pName, pToken,pTitle)
                        }
                    }

                    R.id.btnApply -> {//申请
                        if ("APPLY" == it.optString("status") && it.optString("activeFlag") == "YES") {
                            if (it.optString("applyStatus").endsWith("DENIED")){//被拒绝 - 进入贷款详情
                                val pLogo = it.optString("logo")
                                val pName = it.optString("product")
                                val pToken = it.optString("token")
                                val pTitle = it.optString("name")
                                MullaOrderDetailsAct.start(requireContext(), pLogo, pName, pToken,pTitle)
                                return@MullaOnItemChildClickListener
                            }
                            presenter.checkMullaAllPermissionsAgree()
                        }
                    }
                }
            }
        })
    }

    /**
     * 产品列表
     */
    override fun showMullaProductsView() {
        checkMullaNormalView()
        setMullaTitleBarColor(Color.parseColor("#FFFFFFFF"))
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFFFFFFF"))

        _binding?.textProducts?.setTextColor(Color.parseColor("#FF8027FF"))
        _binding?.textProducts?.textSize = 20f
        _binding?.imgProducts?.visibility = View.VISIBLE

        //新用户
        if (isNewUser()){
            _binding?.scoreTipsLayout?.visibility = View.GONE
        } else {
            _binding?.scoreTipsLayout?.visibility = View.VISIBLE
        }
        _binding?.giftLayout?.visibility = View.VISIBLE
    }

    /**
     * 订单列表
     */
    override fun showMullaAppliedViews() {
        checkMullaNormalView()
        setMullaTitleBarColor(Color.parseColor("#FFF1F3F5"))
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#FFF1F3F5"))

        _binding?.textApplied?.setTextColor(Color.parseColor("#FF8027FF"))
        _binding?.textApplied?.textSize = 20f
        _binding?.imgApplied?.visibility = View.VISIBLE

        _binding?.scoreTipsLayout?.visibility = View.GONE
        _binding?.giftLayout?.visibility = View.GONE
    }

    /**
     * 设置可申请产品列表
     */
    override fun showMullaProductsList(isApply: Boolean,pList: ArrayList<JSONObject>) {
        hideMullaLoading()
        if (pList.size == 0){
            _binding?.recyclerView?.visibility = View.GONE
            _binding?.emptyLayout?.visibility = View.VISIBLE

            var showText = ""
            var startIndex = 0
            when(isApply){
                true -> {
                    showText = String.format(getString(R.string.home_product_apply_empty),getString(R.string.home_product_apply_repay))
                    startIndex = showText.indexOf(getString(R.string.home_product_apply_repay))
                }
                else -> {
                    showText = String.format(getString(R.string.home_product_applied_empty),getString(R.string.home_product_applied_apply))
                    startIndex = showText.indexOf(getString(R.string.home_product_applied_apply))
                }
            }
            val spString = SpannableString(showText)
            spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF8027FF")), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            spString.setSpan(UnderlineSpan(), startIndex, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            _binding?.textEmpty?.text = spString
            return
        }
        _binding?.recyclerView?.visibility = View.VISIBLE
        _binding?.emptyLayout?.visibility = View.GONE
        pAdapter?.data = pList
    }

    /**
     * 设置未选择状态
     */
    private fun checkMullaNormalView() {
        _binding?.textProducts?.setTextColor(Color.parseColor("#FFE0DBEE"))
        _binding?.textProducts?.textSize = 14f
        _binding?.imgProducts?.visibility = View.INVISIBLE

        _binding?.textApplied?.setTextColor(Color.parseColor("#FFE0DBEE"))
        _binding?.textApplied?.textSize = 14f
        _binding?.imgApplied?.visibility = View.INVISIBLE
    }

    /**
     * 进入权限列表预览页面
     */
    override fun showMullaFlowPermissionList() {
        val perListDialog = PermissionListDialog(context,object : PermissionListDialog.IDialogCallback{
            override fun onMullaKefuClick() {
                showMullaKefuDialog("Permission Page")
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Permission Page")
            }
            override fun onMullaLanguageClick() {
                HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"Permission Page")
                showMullaLanguageDialog("Permission Page", onSelectCallback = {
                })
            }

            override fun onMullaDenyClick() {
                //是否是广告渠道
                val isAdSource = SharedHelper.getMullaSPBoolean(SharedHelper.MULLA_SPKEY.MULLA_IS_ADSOURCE)
                //非广告渠道才继续校验进行下一步
                if (!isAdSource){
                    presenter.checkMullaAllPermissionsAgree()
                }
            }

            override fun onMullaAgreeClick() {
                presenter.checkMullaAllPermissionsAgree()
            }
        })
        perListDialog.setCancelable(false)
        perListDialog.setCanceledOnTouchOutside(false)
        perListDialog.show()
    }

    /**
     * 权限验证成功
     */
    override fun showMullaCheckPermissionSuccess() {
        //权限列表操作状态 0未操作  1已同意  -1拒绝
        val perListStatus = SharedHelper.getMullaSPInt(SharedHelper.MULLA_SPKEY.MULLA_PERMISSION_LIST_STATUS)
        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (perListStatus == 1 && XXPermissions.isGranted(requireContext(), Manifest.permission.READ_SMS)){
            //上报设备数据
            TestDataLibInvoke.takeMullaFlowDeviceInfoTypsAction()
        }
        presenter.checkMullaAllStepsAction()
    }

    /**
     * 认证已完成 - 进入申贷页面
     */
    override fun showMullaApplyPage(pName: String, pToken: String, pTitle: String, pLogo: String) {
        hideMullaLoading()
        //进入申贷页前，保存首页点击的产品信息，用于申贷后直接进入详情
        MullaConfigs.clickProductName = pName
        MullaConfigs.clickProductToken = pToken
        MullaConfigs.clickProductTitle = pTitle
        MullaConfigs.clickProductLogo = pLogo
        MullaApplyAct.start(requireContext(),pName,pToken)
    }

    /**
     * 认证未完成 - 进入认证页面
     */
    override fun showMullaProcessStepsPage() {
        hideMullaLoading()
        onIntent(MullaStepsAct::class.java)
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onMullaEvent(event: MullaEventData) {
        super.onMullaEvent(event)
        when(event.eventType){
            MullaEventData.TYPE.MULLA_SHOW_PRODUCTS -> {//显示可申请产品列表
                _binding?.productLayout?.callOnClick()
            }
            MullaEventData.TYPE.MULLA_PRODUCT_REFRESHED -> {//刷新产品列表
                presenter.loadMullaProductListAction()
            }
            MullaEventData.TYPE.MULLA_PRODUCT_FINISHED -> {
                hideMullaLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 是否是新用户
     */
    private fun isNewUser(): Boolean{
        val dataString = SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_PROCESS)
        if (dataString.isEmpty()){
            return true
        }
        val obj = JSONObject(dataString)
        if (!obj.has("userType")){
            return true
        }
        return obj.optString("userType") == "NEW"
    }

    /**
     * 授权
     */
    private fun requestMullaFlowPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        presenter?.checkMullaAllPermissionsAgree()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))

                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_PRODUCT_LIST_END)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}